const mongoose = require("mongoose");

module.exports.addGoods = async newGoods => {
    return await mongoose.model("goodsModel").create(newGoods)
}

module.exports.getGoods = async _id => {
    return await mongoose.model("goodsModel").find(_id)
}

module.exports.deleteGoodsById = async goodsId => {
    return await mongoose.model("goodsModel").deleteOne(goodsId);
}

//修改商品基本信息
module.exports.updateGoodsById = async ({ form2 }) => {
    const { _id, name, classify, pet, price, weight, production, shelfLife, producer, images, desc, shopId } = form2
    const data = await mongoose.model("goodsModel").updateOne({ _id }, { name, classify, pet, price, weight, production, shelfLife, producer, images, desc, shopId })
    return data
}
//查询商品(模糊查询)
module.exports.searchGoods = async ({ name }) => {
    return await mongoose.model("goodsModel").find({ name: { $regex: name, $options: '$i' } })
}
//分页获取商品
module.exports.getGoodsByPage = async ({ adminId, currentPage, pageSize }) => {
    const pageData = {
        currentPage:~~currentPage,  // 当前页码
        pageSize:~~pageSize,  // 每页显示条数
        totalPages:0,   // 总页数
        totalCount:0, // 总条数
        goods:[],
    };
    if(adminId===""){
        pageData.totalCount = await mongoose.model("goodsModel").find().countDocuments();  // 总条数
        pageData.totalPages = Math.ceil(pageData.totalCount / pageSize); // 总页数
        pageData.goods= await mongoose.model("goodsModel")
            .find()
            .skip((currentPage - 1) * pageSize)
            .limit(pageSize - 0)
            .populate("shopId");
        return pageData;
    }
    pageData.totalCount = await mongoose.model("goodsModel").find({ adminId }).countDocuments();  // 总条数
    pageData.totalPages = Math.ceil(pageData.totalCount / pageSize); // 总页数
    pageData.goods= await mongoose.model("goodsModel")
        .find({adminId})
        .skip((currentPage - 1) * pageSize)
        .limit(pageSize - 0)
        .populate("shopId");
    return pageData;
}
